<?php

namespace app\web\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use think\Cookie;

class LoginController extends Controller
{
    public function index()
    {
         if (!Session::has('user_tel')) {
            session::delete('user_tel');
            session::delete('userid');
            return view('index/account');
        }elseif(!Cookie::has('user_tel')){
            $tel = cookie::get('user_tel');
            $data = Db::name('user')->field('pass', true)->where('tel',$tel)->find();
            return view('center/center',['data'=>$data]);
        }else{
            // 个人中心
            $tel = session::get('user_tel');
            $data = Db::name('user')->field('pass', true)->where('tel',$tel)->find();
            // var_dump($data);die;
            return view('center/center',['data'=>$data]);
        }
    }

    public  function login()
    {
        $p = request()->post();
        $tel = $p['tel'];
        $pwd = md5($p['pass']);
        $res = db('user')
            ->field(['id', 'tel'])
            ->where('tel', $tel)
            ->where('pass', $pwd)
            ->where('status','1')
            ->find();
        if($res){
            if(!empty($p['on']))
            {
                Cookie::set("user_tel",$tel,3600);
                Cookie::set("pwd",$pwd,3600);
                Cookie::set("user_id",$res['id'],3600);
            }else{
               Cookie::delete('user_tel');
               Cookie::delete('pwd');
               Cookie::delete('user_id');
            }

            session::set('user_tel',$res['tel']);
            session::set('userid',$res['id']);
            return $this->success('登录成功正在为您跳转～','/center');
        }else{
            return $this->error('账号不存在或密码错误');

        }
    }

     // 注销
    public function logout()
    {
        session::delete('user_tel');
        session::delete('userid');
        Cookie::delete('user_tel');
        Cookie::delete('pwd');
        Cookie::delete('user_id');
        return view('index/account');
    }
}
